package org.jeecg.modules.demo.Kingdee.SaleOrder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceResponseBody;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.taobao.api.ApiException;
import dev.langchain4j.agent.tool.P;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.demo.DPT.service.ITicketService;
import org.jeecg.modules.demo.PaymentRequest.entity.PaymentRequest;
import org.jeecg.modules.demo.PaymentRequest.service.IPaymentRequestService;
import org.jeecg.modules.demo.util.DingTalkUtil;
import org.jeecg.modules.system.entity.SysThirdAccount;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysThirdAccountService;
import org.jeecg.modules.system.service.ISysUserService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.List;

/**
 * 销售订单下推收款单任务（销售订单根据支付渠道更新结算方式）
 * 
 * @Author Scott
 */
@Slf4j
@Component
public class PushSaleOrderToReceiveBillJob implements Job {
	@SneakyThrows
	@Override
	public void execute(JobExecutionContext jobExecutionContext) {

		K3CloudApi api = new K3CloudApi();

// 获取当前日期（不含时间）
		LocalDate today = LocalDate.now();

		// 计算7天前的日期
		LocalDate sevenDaysAgo = today.minusDays(7);

		// 定义格式化模板（yyyy-MM-dd）
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

		// 格式化日期
		String formattedDate = sevenDaysAgo.format(formatter);
//		获取7天内所有现款客户销售订单（微信或者支付宝），收款单号查询为空
		String json = String.format("{\n" +
				"    \"FormId\": \"SAL_SaleOrder\",\n" +
				"    \"FieldKeys\": \"FID,FBILLNO,FSettleModeId.FNumber,F_EC_PayType\",\n" +
				"    \"FilterString\":\"F_EC_PayType in ('weixin','zhifubao') AND (FRelBillNo IS NULL OR FRelBillNo =' ') AND FDate >='"+formattedDate+"' AND FDocumentStatus='C'\",\n" +
				"    \"OrderString\": \"\",\n" +
				"    \"Limit\": 100,\n" +
				"    \"SubSystemId\": \"\"\n" +
				"}");
		JSONArray saleorderList = JSON.parseArray( api.billQuery(json));
		log.info("获取7天内所有现款客户销售订单数量："+saleorderList.size());
		for (Object o : saleorderList) {
			JSONObject saleorder = (JSONObject) o;
			String billNo = saleorder.getString("FBILLNO");
//			检查是否有审核中的收款单
			String json2 = "{\n" +
					"    \"FormId\": \"AR_RECEIVEBILL\",\n" +
					"    \"FieldKeys\": \"FBILLNO\",\n" +
					"    \"FilterString\": \"FSALEORDERNO ='"+billNo+"'\",\n" +
					"    \"OrderString\": \"\",\n" +
					"    \"TopRowCount\": 0,\n" +
					"    \"StartRow\": 0,\n" +
					"    \"Limit\": 1,\n" +
					"    \"SubSystemId\": \"\"\n" +
					"}";
			JSONArray  receivebillList= JSON.parseArray( api.billQuery(json2));
//			存在收款单，不再进行下推
			if(!receivebillList.isEmpty()){
//				log.info("销售订单下推收款单已存在："+billNo);
				continue;
			}
//			没有下推过收款单，进行下推
//			先检查结算方式
			String FSettleModeId = saleorder.getString("FSettleModeId.FNumber");
//				结算方式不存在，更新进单据
			String F_EC_PayType = saleorder.getString("F_EC_PayType");
			if (FSettleModeId == null||(!FSettleModeId.equals("JSFS31_SYS")&&!FSettleModeId.equals("JSFS32_SYS"))){
				String FSettleMode = F_EC_PayType.equals("weixin")?"JSFS31_SYS":"JSFS32_SYS";

				String updateJson="{\n" +
						"    \"NeedUpDateFields\": [\"FSaleOrderFinance\",\"FSettleModeId\"],\n" +
						"    \"Model\":{\n" +
						"        \"FID\": "+saleorder.getString("FID")+",\n" +
						"        \"FSaleOrderFinance\": {\n" +
						"            \"FSettleModeId\": { \"FNumber\": \""+FSettleMode+"\" }\n" +
						"        }\n" +
						"    }";
				String updateResult = api.save("SAL_SaleOrder", updateJson);
				JSONObject result = JSON.parseObject(updateResult);
				Boolean IsSuccess = result.getJSONObject("Result").getJSONObject("ResponseStatus").getBoolean("IsSuccess");
				if (!IsSuccess){
					log.error("结算方式更新失败："+updateResult);
				}else {
					log.info("结算方式更新成功："+updateResult);
				}
			}

			String FACCOUNTTYPE=F_EC_PayType.equals("weixin")?"1":"2";
			String AccountName=F_EC_PayType.equals("weixin")?"京天世纪微信钱包收款":"彩格企业店支付宝";
//		查询银行账号
			String bankjson ="{\n" +
					"    \"FormId\": \"CN_BANKACNT\",\n" +
					"    \"FieldKeys\": \"FNUMBER\",\n" +
					"    \"FilterString\": \"FACCOUNTTYPE ='"+FACCOUNTTYPE+"' AND FNAME ='"+AccountName+"'\"\n" +
					"}";
			JSONArray bankAccount = JSON.parseArray(api.billQuery(bankjson));
			String bankFnumber = bankAccount.getJSONObject(0).getString("FNUMBER");
//			接着进行下推收款单
			String paradata = String.format("{\"Ids\": \"%s\",\"RuleId\": \"SAL_SaleOrderToAR_ReceiveBill\",\"IsDraftWhenSaveFail\":\"true\"}",saleorder.getString("FID"));
			String resultS = api.push("SAL_SaleOrder", paradata);
			JSONObject ResponseStatus = JSON.parseObject(resultS).getJSONObject("Result").getJSONObject("ResponseStatus");
			Boolean aBoolean = ResponseStatus.getBoolean("IsSuccess");
			if(!aBoolean){
				log.error("销售订单下推收款单失败："+resultS);
				continue;
			}else {
				log.info("销售订单下推收款单成功："+resultS);
			}
			JSONObject successEntitys = ResponseStatus.getJSONArray("SuccessEntitys").getJSONObject(0);
//			暂存的单据id
			String Id = successEntitys.getString("Id");
			JSONArray FRECEIVEBILLENTRY = successEntitys.getJSONObject("EntryIds").getJSONArray("FRECEIVEBILLENTRY");
			JSONArray entryResult = new JSONArray();
//			分录拼凑银行账号参数
			for (Object entry : FRECEIVEBILLENTRY) {
				Integer entryId = (Integer) entry;
				JSONObject entryItem = new JSONObject();
				JSONObject FACCOUNTID = new JSONObject();
				FACCOUNTID.put("FNumber",bankFnumber);
				entryItem.put("FACCOUNTID",FACCOUNTID);
				entryItem.put("FEntryID",entryId);
				entryResult.add(entryItem);
			}
//			设置银行账号信息
			String now = DateUtils.now();
			String FREMARK="销售订单（现款客户）自动下推收款单" +now;
			String saveJson="{\n" +
					"    \"NeedUpDateFields\": [\"FREMARK\",\"FRECEIVEBILLENTRY\",\"FACCOUNTID\"],\n" +
					"    \"Model\":{\n" +
					"        \"FID\": "+Id+",\n" +
					"        \"FREMARK\": \""+FREMARK+"\",\n" +
					"\"FRECEIVEBILLENTRY\": "+entryResult.toJSONString()+
					"    }";
			String arReceivebill = api.save("AR_RECEIVEBILL", saveJson);
			log.info("销售订单下推收款单保存结果："+arReceivebill);
//			提交
			String Auditjson = String.format("{\"Ids\": \"%s\"}", Id);
			String result2 = api.submit("AR_RECEIVEBILL", Auditjson);
			log.info("销售订单下推收款单提交结果："+result2);
		}
	}
}
